#pragma once

#include <iostream>
#include <string.h>
#include <string>
#include <cstdio>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
const std::string gpath = "/home/kj";
int gprojID = 0x666;
int gshmsize = 4096;//共享内存的大小
mode_t gmode = 0600;

std::string ToHex(key_t k)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}

class ShareMemory
{
private:
    void CreateShmHelper(int shmflg)
    {
        // 1.创建key
        _key = ::ftok(gpath.c_str(), gprojID);
        if (_key < 0)
        {
            std::cerr << "ftok error" << std::endl;
            return;
        }
        std::cout << "k : " << ToHex(_key) << std::endl;
        // 2.创建共享内存并获取
        // 共享内存也有权限
        _shmid = ::shmget(_key, gshmsize, shmflg);
        if (_shmid < 0)
        {
            std::cerr << "shmget error" << std::endl;
            return;
        }
        std::cout << "shmid : " << _shmid << std::endl;
    }

public:
    ShareMemory():_shmid(-1),_key(0),_addr(nullptr)
    {}
    ~ShareMemory() {}
    void CreateShm()
    {
        if(_shmid == -1)
            CreateShmHelper(IPC_CREAT | IPC_EXCL | gmode);//一定创建一个新的共享内存
    }
    void GetShm()
    {
        CreateShmHelper(IPC_CREAT);//一定能获取到共享内存
    }
    void AttachShm()
    {
        // 将共享内存挂接到自己的地址空间中
        _addr = shmat(_shmid, nullptr, 0); // 返回的是虚拟地址的起始地址
        // std::cout << "attach done" << (long long)ret << std::endl;
        if ((long long)_addr == -1)
            std::cout << "attach done" << (long long)_addr << std::endl;
    }
    void DetachShm()
    {
        // 去关联
        if(_addr != nullptr)
        shmdt(_addr);
        std::cout << "detach done" << std::endl;
    }
    void DeleteShm()
    {
        // 删除共享内存
        shmctl(_shmid, IPC_RMID, nullptr);
    }
    void* GetAddr()
    {
        return _addr; 
    }
private:
    int _shmid;
    key_t _key;
    void* _addr;
};

ShareMemory shm;
struct data
{
    char status[32];
    char lasttime[48];
    char image[4000];
};